﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IceScream.Models;
using IceScream.ViewModels;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using IceScream.Common;

namespace IceScream.Controllers
{
    [Authorize(Users = "admin")]
    public class UserManagerController : Controller
    {
        //
        // GET: /UserManager/
        DataEntities storeDB = new DataEntities();

        public ActionResult Index()
        {
            var user = storeDB.Users.ToList();
            return View(user);
        }

        public ActionResult Edit(int id)
        {
            var user = storeDB.Users.Where(a => a.Id == id).FirstOrDefault();

            var viewModels = new UserManagerViewModels
            {
                User = user
            };

            return View(viewModels);
        }

        [HttpPost]
        public ActionResult Edit(int id,User user, FormCollection collection)
        {
            var uExist = storeDB.Users.Where(a => a.Id == id).FirstOrDefault();
            if (ModelState.IsValid && uExist!=null)
            {
                if (!string.IsNullOrEmpty(user.Password))
                {
                    uExist.Password = UICommon.Encryption(user.Password);
                }
                uExist.FirstName = user.FirstName;
                uExist.LastName = user.LastName;
                uExist.Phone = user.Phone;
                uExist.Email = user.Email;
                uExist.Address = user.Address;

                UpdateModel(user, "Users");
                storeDB.SaveChanges();

                return RedirectToAction("index");
            }

            var viewModels = new UserManagerViewModels
            {
                User = user
            };

            return View(viewModels);
        }
    }
}
